package com.doudou.pay.helper.server.handler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;

/**
 * 通道缓存<br>
 * 通过一个Map来保存终端编号与TCP连接之间的关系
 * @author ouyang
 *
 */
public class ChannelCacheManager {
	
	private static Map<String, Channel> channelMap = new ConcurrentHashMap<String, Channel>();
	
	private static Map<String, String> channelIdMap = new ConcurrentHashMap<String, String>();
	
	/**
	 * 保存通道
	 * @param terminal
	 * @param ctx
	 */
	public static void put(String terminal,ChannelHandlerContext ctx) {
		
		channelIdMap.put(ctx.channel().id().asLongText(), terminal);
		channelMap.put(terminal, ctx.channel());
	}
	
	public static String getAuthToken(ChannelHandlerContext ctx) {
		return channelIdMap.get(ctx.channel().id().asLongText());
	}
	
	/**
	 * 获取通道
	 * @param terminal
	 * @return
	 */
	public static Channel getChannel(String terminal) {
		return channelMap.get(terminal);
	}
	
	/**
	 * 移除通道
	 * @param ctx
	 */
	public static void remove(ChannelHandlerContext ctx) {
		ChannelId id = ctx.channel().id();
		
		//获取终端编号，并移除连接
		String terminal = channelIdMap.get(id.asLongText());
		if(StringUtils.isNotBlank(terminal)){
			channelMap.remove(terminal);
		}
		
		//移除Id与连接对应关系
		channelIdMap.remove(id.asLongText());
	}
	
}
